﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TEL.ClientClasses;
using TEL.ClientClasses.Private;
using TEL.ClientClasses.SipInterfaces;
using TEL.TelPhoneF.Dialogs;
using TEL.TelPhoneF.InfoList;


namespace TEL.TelPhoneF
{
    public partial class Form1 : Form
    {
        const int DISTANCE = 10;
        public static Color BlueSkinColor = Color.FromArgb(54, 149, 246);
        private SipOperation operatorion;
        private SipVizard vizard = null;
        private FrmHistoryCall history;
        private int m_RadiusCone = 50;
        private Point m_ShiftPoint = Point.Empty;
        private Point m_Location = Point.Empty;
        public int RadiusCone
        {
            get { return m_RadiusCone; }
            set { m_RadiusCone = value; }
        }
        private void CreateRegion()
        {
            Paths p = new Paths();
            this.Region = new Region(p.GetMainPath(new Point(0, 0), this.Size));

        }

        private Options Option;

        public static string EventWaitname = "Local\\SimplePhoneClose";
        private void CloseEvent()
        {
            EventWaitHandle ew = new EventWaitHandle(false, EventResetMode.ManualReset, EventWaitname);
            ew.WaitOne();
            this.Invoke(new MethodInvoker(delegate()
                                              {
                                                  IsNotCloce = false;
                                                  this.Close();
                                              }), null);
        }

        public Form1()
        {
            int a = 1 & 2;
            InitializeComponent();
            Thread t = new Thread(CloseEvent);
            t.Start();
            outVolume.Value = Properties.Settings.Default.OutVolume;
            CreateRegion();
            outVolume.ColorValueBar = Form1.BlueSkinColor;
            inVolue.BackColor = Color.FromArgb(38, 38, 38);
            this.BackColor = Color.FromArgb(38, 38, 38);
            Setting.VersionUpdate();
            Option = new Options();
            string s = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
            optionPannel1.btnSet.Click += miSetting_Click;

            vizard = new SipVizard()
                         {
                             InfoPanel = infoPanel1
                             ,
                             BtnPanel = btnPanel1
                             ,
                             LineManager = lineManager1
                             ,
                             PhoneOption = optionPannel1
                         };

            vizard.RegisteringEvent += new EventHandler<RegistrationEventArgs>(vizard_RegisteringEvent);
            vizard.ErrorEvent += new EventHandler<StrErrorEventArgs>(TelSipError);
            vizard.CallLineEvent += new EventHandler<CallEventArgs>(vizard_CallEvent);
            vizard.NumEnterTextChanged += new EventHandler<ReferEventArgs>(vizard_NumEnterTextChanged);
            vizard.AutoRadialEvent += new EventHandler<StringEventArgs>(history_HistoryCall);

            history = new FrmHistoryCall();
            history.HistoryCall += new EventHandler<StringEventArgs>(history_HistoryCall);
            history.FormClosing += new FormClosingEventHandler(history_FormClosing);
            history.ErrorEvent += new EventHandler<StrErrorEventArgs>(TelSipError);
            history.MissingViewChanged += new EventHandler<BoolEventArgs>(history_MissingViewChanged);
            history.SizeChanged += new EventHandler(history_SizeChanged);
            history.Owner = this;
            ELog.SaveToEventLog("Запуск приложения", EventLogEntryType.Information);

            vizard.DisplayNameByPhone += history.FindNameByPhone;
        }

        void history_SizeChanged(object sender, EventArgs e)
        {
            SetHistoryLocation();
        }

        private void SetHistoryLocation()
        {
            Size hl = new Size(-1 * (history.Width), 50);
            history.Location = this.Location + hl;
        }

        void vizard_NumEnterTextChanged(object sender, ReferEventArgs e)
        {
            try
            {
                Contact contact = history.FindFirstContact(e.NumberPhoneSource);
                infoPanel1.SetTempContact(contact);
            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  btnPanel1_NumberEvent", error, false));
            }
        }

        private bool m_missingViewState = false;
        public bool MissingViewState
        {
            get { return m_missingViewState; }
            private set
            {
                m_missingViewState = value;
                SetNotifyIcon();
            }
        }
        void history_MissingViewChanged(object sender, BoolEventArgs e)
        {
            infoPanel1.SetMissing(e.Message);
            MissingViewState = e.Message;
        }

        void history_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                miHistoryCall.Checked = false;
            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  history_FormClosing", error, false));
            }
        }

        void history_HistoryCall(object sender, StringEventArgs e)
        {
            try
            {

                this.Invoke(new MethodInvoker(delegate()
                {
                    vizard.ClearNumber();
                    btnPanel1.EnterNumber(e.Message);
                    optionPannel1.AutoAcceptMainClick();
                }), null);

            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  history_HistoryCall", error, false));
            }
        }

        void vizard_RegisteringEvent(object sender, RegistrationEventArgs e)
        {
            try
            {
                if (e.State == RegistrationState.Disposed)
                {
                    GC.Collect();
                    if (m_autoConnect)
                    {
                        InitializeSip();
                    }
                }

                if (e.State == RegistrationState.Registered)
                {
                    IsRegistrated = true;
                    operatorion.CreateLines(6);
                    infoPanel1.SetLabelError(string.Empty);
                }
                else
                    IsRegistrated = false;
                SetconnectMenuItemEnable(e.State != RegistrationState.Unregistered);
            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  vizard_RegisteringEvent", error, false));
            }
        }

        private List<string> m_BallLineCall = new List<string>();

        private void ToHistory(CallEventArgs e)
        {
            try
            {
                if (!e.Caller.IsOutCall && e.Caller.State == CallState.WaitingToAccept)
                {
                    ContactCall contactCall = new ContactCall()
                                                  {
                                                      Date = e.Caller.StartTime,
                                                      State = ContactCallState.Missing,
                                                      ContactName = e.Caller.DisplayName,
                                                      ContactPhone = SipVizard.GetNumberFromSip(e.Caller.LineCall)
                                                  };
                    history.AddCallHistory(contactCall);
                }

                if (!e.Caller.IsOutCall && !e.Caller.IsWasActive && e.Caller.State == CallState.Terminated)
                {
                    ContactCall contactCall = new MissingCall()
                    {
                        Date = e.Caller.StartTime,
                        State = ContactCallState.Missing,
                        ContactName = e.Caller.DisplayName,
                        ContactPhone = SipVizard.GetNumberFromSip(e.Caller.LineCall)
                    };
                    history.AddCallHistory(contactCall);
                }

                if (!e.Caller.IsOutCall && e.Caller.State == CallState.Active)
                {
                    history.UpdateStateHistory(e.Caller.StartTime, ContactCallState.Accepted);
                }

                if (e.Caller.IsOutCall && e.Caller.State == CallState.Ringing)
                {
                    ContactCall contactCall = new ContactCall()
                                                  {
                                                      Date = e.Caller.StartTime,
                                                      State = ContactCallState.Out,
                                                      ContactPhone =
                                                          ClientClasses.SipVizard.GetNumberFromSip(e.Caller.LineCall)
                                                  };
                    history.AddCallHistory(contactCall);
                }
                if (e.Caller.State == CallState.Active) history.DeleteMissing(SipVizard.GetNumberFromSip(e.Caller.LineCall));
            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  ToHistory", error, false));
            }
        }

        private void showBalloon(Call call)
        {
            this.Invoke(new MethodInvoker(delegate()
                                              {
                                                  frmBalloonTip f = new frmBalloonTip();
                                                  f.DisplayName = call.DisplayName;
                                                  f.Number = SipVizard.GetNumberFromSip(call.LineCall);
                                                  f.Cansel += new EventHandler(f_Cansel);
                                                  f.Ansver += new EventHandler(f_Ansver);
                                                  f.Show();
                                              }), null);
        }

        void f_Ansver(object sender, EventArgs e)
        {
            vid = true;
            try
            {
                lineManager1.ActiveLine.AcceptCall();
            }
            catch (Exception)
            {

            }
        }

        void f_Cansel(object sender, EventArgs e)
        {
            try
            {
                if (lineManager1.ActiveLine != null)
                    lineManager1.ActiveLine.CallTerminated();
            }
            catch (Exception)
            {
            }

        }

        void vizard_CallEvent(object sender, CallEventArgs e)
        {
            if (e.Caller == null)
            {
                return;
            }

            try
            {
                // Invoke(new MethodInvoker(delegate() { ToHistory(e); }), null);
                Task.Factory.StartNew(delegate() { ToHistory(e); });
            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  operatorion_CallEvent при записи истории", error, false));
            }

            try
            {
                if (operatorion.DND || operatorion.IsCall) return;
                if (e.Caller.State == CallState.WaitingToAccept)
                {
                    if (!m_BallLineCall.Contains(e.Caller.LineCall))
                    {
                        m_BallLineCall.Add(e.Caller.LineCall);
                        string tipText = string.Format("{0}\n\r{1}", e.Caller.DisplayName,
                                                       SipVizard.GetNumberFromSip(e.Caller.LineCall));
                        notifyIcon.BalloonTipText = tipText;
                        notifyIcon.Tag = e.Caller.LineCall;
                        // notifyIcon.ShowBalloonTip(5*1000);
                        showBalloon(e.Caller);
                    }
                }
                if (e.Caller.State == CallState.Terminated)
                {
                    m_BallLineCall.Remove(e.Caller.LineCall);

                }
            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  operatorion_CallEvent", error, false));
            }
        }

        private void InitializeSip()
        {
            try
            {
                lineManager1.TransferLine = null;
                lineManager1.XferLine = null;

                if (!SipOperation.AudioOutCkek())
                {
                    infoPanel1.SetLabelError("Устройство вывода звука не найдено!");
                    ELog.SaveToEventLog("Устройство вывода звука не найдено!", EventLogEntryType.Warning);
                    btnPanel1.Enabled = false;
                    operatorion = null;
                    return;
                }

                if (!SipOperation.AudioInCkek())
                {
                    infoPanel1.SetLabelError("Микрофон не найден!");
                    ELog.SaveToEventLog("Микрофон не найден!", EventLogEntryType.Warning);
                    btnPanel1.Enabled = false;
                    operatorion = null;
                    return;
                }

                ISipAccount property = new Setting().LoadContent(false);
                operatorion = new SipOperation(property, Option);
                optionPannel1.TransferOption = Option.Transfer;
                
                infoPanel1.SetLabelError("");
                operatorion.DNDCanged += new EventHandler<BoolEventArgs>(operatorion_DNDCanged);
                operatorion.SetOutVolume(outVolume.Value);
                operatorion.TelSipError += new EventHandler<StrErrorEventArgs>(TelSipError);
                operatorion.ResponseStatusEvent += new EventHandler<SipResponseEventArgs>(operatorion_ResponseStatusEvent);
                vizard.Operation = operatorion;
                
                ELog.SaveToEventLog("Попытка установить соединения с сервером", EventLogEntryType.Information);
                if (!operatorion.Connected) operatorion.Connection();

            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  operatorion_CallEvent", error, false));
            }
        }

        void operatorion_ResponseStatusEvent(object sender, SipResponseEventArgs e)
        {
            infoPanel1.SetLabelError(string.Format("({0}) - {1}", e.StatusCode, e.Message));
        }

        void TelSipError(object sender, StrErrorEventArgs e)
        {
            try
            {

                if (operatorion.SimpleLog != null)
                    operatorion.SimpleLog.Write(LogType.Error, "Error in form1",
                                                string.Format("{0} ({1})", e.StringError, e.Error.Message));
                if (e.PublishError)
                    MessageBox.Show(string.Format("{0} ({1})", e.StringError, e.Error.Message), "Ошибка",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                Win32Exception win32Exception = e.Error as Win32Exception;
                if (win32Exception == null) win32Exception = e.Error.InnerException as Win32Exception;

                if (win32Exception != null && win32Exception.ErrorCode == 10048)
                {
                    MessageBox.Show(
                        "Порт указанный в настройках программы занят! \r Перейдите в настройки и введите другой свободный порт.",
                        "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            catch (Exception)
            {
            }
        }

        void operatorion_DNDCanged(object sender, BoolEventArgs e)
        {
            try
            {
                DndMenuItem.Checked = e.Message;
                SetNotifyIcon();

            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  operatorion_DNDCanged", error, false));
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            bool b = true;
            while (!Setting.CheckSipSetting() && b)
            {
                b = AccountSetting();
            }
            if (Setting.CheckSipSetting()) InitializeSip();

            notifyIcon.Visible = true;
            infoPanel1.KeyDown += Form1_KeyDown;
            lineManager1.KeyDown += Form1_KeyDown;
            optionPannel1.KeyDown += Form1_KeyDown;
            outVolume.KeyDown += Form1_KeyDown;
            SetNotifyIcon();
            history.OnMissingViewChanged();
            Point p = Properties.Settings.Default.LocationPoint;
            if (p != Point.Empty) Location = p;
        }

        private bool IsNotCloce = true;

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (IsNotCloce)
                {
                    e.Cancel = true;
                    vid = false;

                }
                else
                {
                    if (history != null) history.Close();
                    //if (operatorion != null && operatorion.Connected)
                    operatorion.Dispose();
                    vizard = null;
                    operatorion = null;
                    history.Owner = null;
                    history = null;
                    e.Cancel = false;

                    ELog.SaveToEventLog("Закрытие приложения", EventLogEntryType.Information);
                }
            }
            catch (Exception)
            {
            }
        }

        void answeringMachine_Closed(object sender, EventArgs e)
        {
            try
            {
                if (vizard == null) return;
                vizard.AnsweringMachine = null;
            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  answeringMachine_Closed", error, false));
            }
        }

        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {

        }

        private bool AccountSetting()
        {
            Setting setting = new Setting();

            DialogSipAccount sipProperty = (DialogSipAccount)setting.LoadContent(true);
            bool res = sipProperty.ShowDialog() == DialogResult.OK;
            if (res)
            {
                setting.SaveContent(sipProperty);
                if (operatorion != null && operatorion.Connected)
                {
                    operatorion.Dispose();
                }
                //InitializeSip(); 
            }
            return res;
        }

        private void miSetting_Click(object sender, EventArgs e)
        {
            AccountSetting();
            if (operatorion == null || operatorion.StackState == -1 || operatorion.StackState == 3)
                InitializeSip();
        }

        private void miAnswerSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (vizard == null) throw new ArgumentNullException("vizard");
                FrmAnsweringMachine answeringMachine = new FrmAnsweringMachine();
                answeringMachine.Closed += new EventHandler(answeringMachine_Closed);
                vizard.AnsweringMachine = answeringMachine;

                answeringMachine.ShowDialog();
            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  miAnswerSave_Click", error, false));
            }
        }

        private FormWindowState m_OldFormState;

        private bool m_vid = true;

        private bool vid
        {
            get { return m_vid; }
            set
            {
                try
                {
                    m_vid = value;
                    if (!value) this.Hide();
                    else
                    {
                        this.Show();
                        this.WindowState = FormWindowState.Normal;
                        this.Activate();
                    }
                    if (history != null)
                    {
                        history.Vid = value && miHistoryCall.Checked;
                        if (!history.Vid && MissingViewState) miHistoryCall.PerformClick();
                    }
                }
                catch (Exception error)
                {
                    TelSipError(this, new StrErrorEventArgs("MainForm  vid", error, false));
                }
            }
        }

        private void notifyIcon_MouseClick(object sender, MouseEventArgs e)
        {
            //проверяем, какой кнопкой было произведено нажатие
            if (e.Button == MouseButtons.Left)//если левой кнопкой мыши
            {
                if (MissingViewState)
                    vid = true;
                else
                    vid = !vid;
            }
        }

        private void notifyIcon_BalloonTipClicked(object sender, EventArgs e)
        {
            try
            {
                vid = true;
                optionPannel1.btnMain.PerformClick();

            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  notifyIcon_BalloonTipClicked", error, false));
            }
        }

        private void OpenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WindowState = m_OldFormState;
        }

        private void closeMenuItem_Click(object sender, EventArgs e)
        {
            //IsNotCloce = false;
            if (history != null)
            {
                history.Hide();
                // history.Close();
            }
            try
            {
                EventWaitHandle ew = EventWaitHandle.OpenExisting(EventWaitname);
                ew.Set();
            }
            catch (Exception)
            {
            }
        }

        private bool m_autoConnect = true;

        private bool m_isRegistrated;

        private void SetconnectMenuItemEnable(bool enable)
        {
            try
            {

                this.Invoke(new MethodInvoker(delegate()
                                                       {
                                                           connectMenuItem.Enabled = enable;
                                                           notifyConnection.Enabled = enable;
                                                       }), null);

            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  SetconnectMenuItemEnable", error, false));
            }
        }

        private void SetNotifyIcon()
        {
            double iconKoef = 0.75;
            try
            {
                System.Drawing.Bitmap icon = null;
                if (!IsRegistrated)
                {
                    notifyIcon.Icon = Properties.Resources.telephonered;
                    icon = Properties.Resources.telephonered.ToBitmap();
                }
                else
                {
                    if (operatorion != null && operatorion.DND) icon = Properties.Resources.telephone_dnd.ToBitmap();
                    else
                    {
                        icon = Properties.Resources.telephone.ToBitmap();
                    }
                }

                if (MissingViewState)
                {
                    Graphics graphics = Graphics.FromImage(icon);
                    System.Drawing.Size recSize = new Size((int)(icon.Width * iconKoef), (int)(icon.Height * iconKoef));
                    Point local = new Point(icon.Width - recSize.Width, icon.Height - recSize.Height);
                    graphics.DrawImage(Properties.Resources.user_red, new Rectangle(local, recSize));
                }
                notifyIcon.Icon = System.Drawing.Icon.FromHandle(icon.GetHicon());
            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  SetNotifyIcon", error, false));
            }
        }

        protected bool IsRegistrated
        {
            get { return m_isRegistrated; }
            set
            {
                if (m_isRegistrated != value)
                    try
                    {
                        this.Invoke(new MethodInvoker(delegate()
                                                          {
                                                              m_isRegistrated = value;
                                                              if (m_isRegistrated)
                                                              {
                                                                  connectMenuItem.Image =
                                                                      Properties.Resources.un_connect_16;
                                                                  connectMenuItem.Text = "Разъединить";
                                                                  notifyConnection.Image =
                                                                      Properties.Resources.un_connect_16;
                                                                  notifyConnection.Text = "Разъединить";
                                                              }
                                                              else
                                                              {
                                                                  connectMenuItem.Image = Properties.Resources.connect_16;
                                                                  connectMenuItem.Text = "Соединить";
                                                                  notifyConnection.Image = Properties.Resources.connect_16;
                                                                  notifyConnection.Text = "Соединить";
                                                              }
                                                              SetNotifyIcon();
                                                          }), null);
                    }
                    catch (Exception error)
                    {
                        TelSipError(this, new StrErrorEventArgs("MainForm  SetNotifyIcon", error, false));
                    }
            }
        }

        private void connectMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsRegistrated)
                {
                    m_autoConnect = false;
                    if (operatorion != null && operatorion.Connected) operatorion.Dispose();
                }
                else
                {
                    m_autoConnect = true;
                    InitializeSip();
                }
            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  connectMenuItem_Click", error, false));
            }
        }

        private void DndMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                optionPannel1.SetDND(!DndMenuItem.Checked);
            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  DndMenuItem_Click", error, false));
            }

        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {

        }

        private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new AboutBox().ShowDialog();
        }

        private void miHistoryCall_Click(object sender, EventArgs e)
        {
            try
            {
                miHistoryCall.Checked = !miHistoryCall.Checked;
                history.Vid = miHistoryCall.Checked;

                panelHistory.BackgroundImage = history.Vid ? Properties.Resources.lbtn : Properties.Resources.rbtn;
                SetHistoryLocation();
                m_ShiftPoint = new Point(1, 1);
                if (history.Vid && Location.X == 0) Location += new Size(1, 0);
                if (!history.Vid && history.Location.X == 0) Location += new Size(history.Width * -1, 0);
                m_ShiftPoint = Point.Empty;
            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  miHistoryCall_Click", error, false));
            }

        }

        public void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Add)
                {
                    if (outVolume.Value < 100) outVolume.Value++;
                    return;
                }

                if (e.KeyCode == Keys.Subtract)
                {
                    if (outVolume.Value > 0) outVolume.Value--;
                    return;
                }
                if (btnPanel1.BtnPanel_KeyDown(e)) return;
                if (lineManager1.BtnPanel_KeyDown(e)) return;
                if (optionPannel1.BtnPanel_KeyDown(e)) return;
                if (infoPanel1.BtnPanel_KeyDown(e)) return;
            }
            catch (Exception)
            {
            }


        }

        private void outVolume_ValueChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.OutVolume = outVolume.Value;
            Properties.Settings.Default.Save();
            if (operatorion != null)
                operatorion.SetOutVolume(outVolume.Value);
        }

        private void infoPanel1_pictureMissClick(object sender, EventArgs e)
        {
            if (!history.Vid && MissingViewState) miHistoryCall.PerformClick();
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void panelHeader_MouseDown(object sender, MouseEventArgs e)
        {
            m_ShiftPoint = this.PointToScreen(e.Location);
            m_Location = Location;
        }

        private void panelHeader_MouseUp(object sender, MouseEventArgs e)
        {
            m_ShiftPoint = Point.Empty;
            m_Location = Point.Empty;
            Properties.Settings.Default.LocationPoint = Location;
            Properties.Settings.Default.Save();
        }

        private void panelHeader_MouseMove(object sender, MouseEventArgs e)
        {
            if (m_ShiftPoint == Point.Empty || m_Location == Point.Empty) return;
            Point p = this.PointToScreen(e.Location);
            System.Drawing.Size s = new Size(p.X - m_ShiftPoint.X, p.Y - m_ShiftPoint.Y);
            this.Location = m_Location + s;
            // m_ShiftPoint = p;

        }

        private void optionPannel1_RedialEvent(object sender, EventArgs e)
        {
            try
            {
                miHistoryCall_Click(sender, e);
                if (history.Vid)
                    history.SetFilterOut();
            }
            catch (Exception error)
            {
                TelSipError(this, new StrErrorEventArgs("MainForm  miHistoryCall_Click", error, false));
            }
        }

        private void Form1_LocationChanged(object sender, EventArgs e)
        {
            SetHistoryLocation();
        }

        private void Form1_Activated(object sender, EventArgs e)
        {
            if (history.Vid)
            {
                history.Show();
                SetHistoryLocation();
            }
        }

        protected override void WndProc(ref Message m)
        {

            try
            {
                if (m.Msg == 0x0046 /* WM_WINDOWPOSCHANGING */ && m_ShiftPoint != Point.Empty)
                {
                    Rectangle workArea = Screen.FromPoint(m_ShiftPoint).WorkingArea;
                    // SystemInformation.WorkingArea;
                    Rectangle rect = (Rectangle)Marshal.PtrToStructure((IntPtr)(IntPtr.Size * 2 + m.LParam.ToInt64()), typeof(Rectangle));

                    if (rect.X <= workArea.Left + DISTANCE + (history.Vid ? history.Width : 0))
                        Marshal.WriteInt32(m.LParam, IntPtr.Size * 2, workArea.Left + (history.Vid ? history.Width : 0));

                    if (rect.X + rect.Width >= workArea.Width - DISTANCE)
                        Marshal.WriteInt32(m.LParam, IntPtr.Size * 2, workArea.Right - rect.Width);

                    if (rect.Y <= workArea.Top + DISTANCE)
                        Marshal.WriteInt32(m.LParam, IntPtr.Size * 2 + 4, workArea.Top);

                    if (rect.Y + rect.Height >= workArea.Height - DISTANCE)
                        Marshal.WriteInt32(m.LParam, IntPtr.Size * 2 + 4, workArea.Bottom - rect.Height);
                }
            }
            catch (Exception)
            {
            }


            base.WndProc(ref m);
        }

        private void OptionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Options o = this.Option.Clone();
            DialogOptions dialogOptions = new DialogOptions() { Options = Option };

            if (dialogOptions.ShowDialog() == DialogResult.OK)
            {
                Option.Save();
                optionPannel1.TransferOption = this.Option.Transfer;
                if (operatorion != null) operatorion.SignalVolumeToLines();
            }
            else
            {
                this.Option = o;
            }
        }

    }
}